package com.jmp.im;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 第三方回调
 */
@Slf4j
public class ImNotifyClient {
    public static final String TYPE = "yunxin";
    private String appKey;
    private String appSecret;

    public ImNotifyClient() {
        this("ca8aa56ec29ed73cb02cb144da272a8c", "32b682e6afe7");
    }

    public ImNotifyClient(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    public boolean check(HttpServletRequest request, String resquestBody) {
        String AppKey = request.getHeader("AppKey");
        String CurTime = request.getHeader("CurTime");
        String MD5 = request.getHeader("MD5");
        String CheckSum = request.getHeader("CheckSum");

        if (!StringUtils.equals(AppKey, appKey)) {
            log.error("appKey check error: {} not equals {}", AppKey, appKey);
            return false;
        }

        String md5 = CheckSumBuilder.getMD5(resquestBody);
        if (!StringUtils.equals(MD5, md5)) {
            log.error("md5 check error: {} not equals {}", MD5, md5);
            return false;
        }

        String checkSumCheck = CheckSumBuilder.getCheckSum(appSecret, MD5, CurTime);
        if (!StringUtils.equals(CheckSum, checkSumCheck)) {
            log.error("checkSumCheck check error: {} not equals {}", CheckSum, checkSumCheck);
            return false;
        }
        return true;
    }

    public void success(HttpServletResponse response) {
        NotifyResult result = new NotifyResult(0);
        response(response, JSON.toJSONString(result));
    }

    private void response(HttpServletResponse response, String result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(result);
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
